/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package db.server.BUS;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 *
 * @author QuangKhai
 */
public class DBServerBUS {
    //Xoa file
    public void Delete(File fileName){
        //La thu muc
        if (fileName.isDirectory()){
            //Lay ra danh sach duong dan den cac item con.
            String files[] = fileName.list();

            //Duyet de qui cac item con
            for(int i = 0; i < files.length; i++) {
                Delete(new File(fileName, files[i]));
            }

            fileName.delete();
        }
        else{ //La tap tin hoac khong ton tai
            if(!fileName.exists()) { //Duong dan nguon khong ton tai
                System.out.println("Khong ton tai file/ folder can xoa!");
                System.exit(0);
            }
            else { //La tap tin
                fileName.delete();
            }
        }
    }    

    //Copy
    public void copy(File srcPath, File dstPath) throws IOException{        
        //La thu muc
        if (srcPath.isDirectory()){
            //Thu muc dich khong ton tai. Tao thu muc moi
            if (!dstPath.exists()){
                dstPath.mkdir();
            }

            //Lay ra danh sach duong dan den cac item con.
            String files[] = srcPath.list();

            //Duyet de qui cac item con
            for(int i = 0; i < files.length; i++) {
                copy(new File(srcPath, files[i]), new File(dstPath, files[i]));
            }
        } else{ //La tap tin hoac khong ton tai
            if(!srcPath.exists()) { //Duong dan nguon khong ton tai
                System.exit(0);
            } else { //La tap tin
                InputStream in = new FileInputStream(srcPath);
                OutputStream out;

                if(dstPath.isDirectory()){
                    out = new FileOutputStream(new File(dstPath, srcPath.getName()));
                }
                else{
                    out = new FileOutputStream(dstPath);
                }
                // Transfer bytes from in to out
                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }

                in.close();
                out.close();
            }
        }
    }
}
